<?php

function is_alpha($c) { return ('a' <= $c && $c <= 'z') || ('A' <= $c && $c <= 'Z'); }
function is_digit($c) { return '0' <= $c && $c <= '9'; }

// all functions return true or error string

function check_username($s) {
    $n = strlen($s);
    if ($n < 2) return "username must be at least 2 characters long";
    if ($n > 32) return "username must be at most 32 characters long";
    if ($s[0] == '-') return "username must not start with a hyphen";
    if ($s[$n - 1] == '-') return "username must not end with a hyphen";
    $was_alpha = false;
    for ($i = 0; $i < $n; $i++) {
        $c = $s[$i];
        if (!is_alpha($c) && !is_digit($c) && $c !== '-' && $c !== '_') {
            return "username must consist of characters a-z,A-Z,0-9,-,_";
        }
        if (is_alpha($c)) {
            $was_alpha = true;
        }
    }
    if (!$was_alpha) return "username must contain at least one letter";
    if (username_exists($s)) return "this username is already occupied";
    return true;
}

function check_password($s) {
    $n = strlen($s);
    if ($n < 3) return "password must be at least 3 characters long";
    return true;
}

function check_firstlastname($s, $firstlast) {
    if (empty($s)) return $firstlast." name must not be empty";
    $n = strlen($s);
    if ($n > 32) return $firstlast." name must be at most 32 characters long";
    $was_alpha = false;
    for ($i = 0; $i < $n; $i++) {
        $c = $s[$i];
        if (!is_alpha($c) && $c !== '-' && $c !== ' ' && $c !== '\'') {
            return $firstlast." name must consist of characters a-z,A-Z, ,-,'";
        }
        if (is_alpha($c)) {
            $was_alpha = true;
        }
    }
    if (!$was_alpha) return $firstlast." name must contain at least one letter";
    return true;
}

function check_firstname($s) {
    return check_firstlastname($s, "first");
}

function check_lastname($s) {
    return check_firstlastname($s, "last");
}


?>
